package com.ifonly.activerecord.proxy;

import com.ifonly.activerecord.sql.SqlFormatter;
import com.ifonly.config.Configuration;
import com.ifonly.reports.Reporter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-03 15:00
 * @since JDK 1.6
 */
public class ConnectionSqlReportHandler implements InvocationHandler {
    private Connection target;
    private Reporter reporter;

    public ConnectionSqlReportHandler(Connection target) {
        this.target = target;
        this.reporter = Configuration.getInstance().getReporter();
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("prepareStatement")) {
            if (args != null && args.length > 0) {
                String sql = args[0].toString();
                reporter.report("SQL: " + SqlFormatter.format(sql));
            }
        }
        return method.invoke(this.target, args);
    }

}
